package com.xmartjoy.java.david;

import org.hibernate.*;

public class UserDAOImpl implements UserDAO {
    @Override
    public void save(User user) {
        Session session = HibernateUtil.getSession();
        Transaction tx =session.beginTransaction();
        try{
            session.save(user);
            tx.commit();
        }catch (Exception e){
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
           // HibernateUtil.shutdown();
        }
//        Session s = null;
//        Transaction tx = null;
//        try{
//            HibernateUtil.init();
//            s=HibernateUtil.getSession();
//            tx=s.beginTransaction();
//            s.save(user);
//            tx.commit();
//        }finally {
//            if(s !=null)
//                s.close();
//        }
    }

    @Override
    public User findById(int id) {
        User u = null;
        Session s = HibernateUtil.getSession();
        Transaction tx = s.beginTransaction();
        try{
            u=(User)s.get(User.class,id);
            tx.commit();
        }catch (Exception e){
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
           // HibernateUtil.shutdown();
        }
        return u;
    }

    @Override
    public void delete(User user) {
        Session s=HibernateUtil.getSession();
        Transaction tx = s.beginTransaction();
        try{
            s.delete(user);
            tx.commit();
        }catch (Exception e){
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
           // HibernateUtil.shutdown();
        }

    }

    @Override
    public void update(User user) {
        Session s=HibernateUtil.getSession();
        Transaction tx = s.beginTransaction();
        try{
            s.update(user);
            tx.commit();
        }catch (Exception e){
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
          //  HibernateUtil.shutdown();
        }
    }
}
